package org.dromara.app.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.tencentcloudapi.common.AbstractModel;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.faceid.v20180301.FaceidClient;
import com.tencentcloudapi.faceid.v20180301.models.IdCardVerificationRequest;
import com.tencentcloudapi.faceid.v20180301.models.IdCardVerificationResponse;
import io.rong.RongCloud;
import io.rong.methods.user.User;
import io.rong.models.Result;
import io.rong.models.response.TokenResult;
import io.rong.models.user.UserModel;
import jakarta.servlet.http.HttpServletRequest;
import org.dromara.app.appParams.*;
import org.dromara.app.appReturn.*;
import org.dromara.app.config.AppRongYunConfig;
import org.dromara.app.config.AppUserActivityConfig;
import org.dromara.app.cssUtils.CssExceptionDescription;
import org.dromara.app.cssUtils.CssUtils;
import org.dromara.app.cssUtils.RedisServiceUtils;
import org.dromara.app.domain.*;
import org.dromara.app.domain.sys.SysSumData;
import org.dromara.app.domain.sys.SysSumReturn;
import org.dromara.app.mapper.*;
import org.dromara.app.service.IBfAppUserActivityService;
import org.dromara.app.service.IBfExperienceLogService;
import org.dromara.app.service.ISkNickHeadService;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.dromara.app.domain.bo.SkAppUserBo;
import org.dromara.app.domain.vo.SkAppUserVo;
import org.dromara.app.service.ISkAppUserService;

import java.awt.image.BufferedImage;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * app用户Service业务层处理
 *
 * @author Evacuation
 * @date 2024-07-23
 */
@RequiredArgsConstructor
@Service
public class SkAppUserServiceImpl implements ISkAppUserService {

    private final SkAppUserMapper baseMapper;

    private final AppRongYunConfig appRongYunConfig;

    private final SkFansUserMapper skFansUserMapper;

    private final SkDarenBrowsingHistoryMapper skDarenBrowsingHistoryMapper;

    private final SkUserTrendsMapper skUserTrendsMapper;

    private final SkYueDanOrderMapper skYueDanOrderMapper;

    private final SkVipPriceMapper skVipPriceMapper;

    private final SkDaRenApplyMapper skDaRenApplyMapper;

    private final SkYueJuUserMapper skYueJuUserMapper;

    private final IBfExperienceLogService iBfExperienceLogService;

    private final SkNickHeadMapper skNickHeadMapper;

    private final IBfAppUserActivityService iBfAppUserActivityService;

    @Value("${txyun.app-id}")
    private  String appId;

    @Value("${txyun.secret-id}")
    private  String secretId;

    @Value("${txyun.sfrz-url}")
    private  String sfrzUrl;

    @Value("${txyun.secretKey}")
    private  String secretKey;



    /**
     * 查询app用户
     *
     * @param id 主键
     * @return app用户
     */
    @Override
    public SkAppUserVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询app用户列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return app用户分页列表
     */
    @Override
    public TableDataInfo<SkAppUserVo> queryPageList(SkAppUserBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SkAppUser> lqw = buildQueryWrapper(bo);
        Page<SkAppUserVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的app用户列表
     *
     * @param bo 查询条件
     * @return app用户列表
     */
    @Override
    public List<SkAppUserVo> queryList(SkAppUserBo bo) {
        LambdaQueryWrapper<SkAppUser> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SkAppUser> buildQueryWrapper(SkAppUserBo bo) {
        //判断是否城市代理账户
        LoginUser user = LoginHelper.getLoginUser();
        if (user.getRolePermission().contains("cityAgent")){
            //是城市代理人
            bo.setCity(user.getCity());
        }
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SkAppUser> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getId() != null, SkAppUser::getId, bo.getId());
        lqw.eq(bo.getUserType() != null, SkAppUser::getUserType, bo.getUserType());
        lqw.eq(StringUtils.isNotBlank(bo.getHeadImage()), SkAppUser::getHeadImage, bo.getHeadImage());
        lqw.like(StringUtils.isNotBlank(bo.getPhone()),SkAppUser::getPhone, bo.getPhone());
        lqw.like(StringUtils.isNotBlank(bo.getNickName()), SkAppUser::getNickName, bo.getNickName());
        lqw.eq(StringUtils.isNotBlank(bo.getSex()), SkAppUser::getSex, bo.getSex());
        lqw.eq(StringUtils.isNotBlank(bo.getBirthday()), SkAppUser::getBirthday, bo.getBirthday());
        lqw.eq(StringUtils.isNotBlank(bo.getHeight()), SkAppUser::getHeight, bo.getHeight());
        lqw.eq(StringUtils.isNotBlank(bo.getEducation()), SkAppUser::getEducation, bo.getEducation());
        lqw.eq(StringUtils.isNotBlank(bo.getBeGoodAt()), SkAppUser::getBeGoodAt, bo.getBeGoodAt());
        lqw.eq(StringUtils.isNotBlank(bo.getPersonalityTag()), SkAppUser::getPersonalityTag, bo.getPersonalityTag());
        lqw.eq(StringUtils.isNotBlank(bo.getVipTime()), SkAppUser::getVipTime, bo.getVipTime());
        lqw.eq(StringUtils.isNotBlank(bo.getPersonalitySign()), SkAppUser::getPersonalitySign, bo.getPersonalitySign());
        lqw.eq(bo.getVipType() != null, SkAppUser::getVipType, bo.getVipType());
        lqw.eq(StringUtils.isNotBlank(bo.getWelcome()), SkAppUser::getWelcome, bo.getWelcome());
        lqw.like(StringUtils.isNotBlank(bo.getRealName()), SkAppUser::getRealName, bo.getRealName());
        lqw.eq(StringUtils.isNotBlank(bo.getIdCard()), SkAppUser::getIdCard, bo.getIdCard());
        lqw.eq(bo.getPrice() != null, SkAppUser::getPrice, bo.getPrice());
        lqw.eq(StringUtils.isNotBlank(bo.getPassword()), SkAppUser::getPassword, bo.getPassword());
        lqw.eq(StringUtils.isNotBlank(bo.getJyPassword()), SkAppUser::getJyPassword, bo.getJyPassword());
        lqw.eq(bo.getIsTgDaren() != null, SkAppUser::getIsTgDaren, bo.getIsTgDaren());
        lqw.eq(bo.getIsHehuo() != null, SkAppUser::getIsHehuo, bo.getIsHehuo());
        lqw.eq(StringUtils.isNotBlank(bo.getCity()),SkAppUser::getCity,bo.getCity());
        return lqw;
    }

    /**
     * 新增app用户
     *
     * @param bo app用户
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(SkAppUserBo bo) {
        SkAppUser add = MapstructUtils.convert(bo, SkAppUser.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改app用户
     *
     * @param bo app用户
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(SkAppUserBo bo) {
        SkAppUser update = MapstructUtils.convert(bo, SkAppUser.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SkAppUser entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除app用户信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 手机号码登录注册
     *
     * @param appReqister
     * @return
     */
    @Override
    public AppUserInfo appLogin(AppLoginReqister appReqister) {
        AppUserInfo appUserInfo = new AppUserInfo();
        Object sendCode = RedisUtils.getCacheObject(RedisServiceUtils.SendCode(appReqister.getPhone()));
        int isZhuCe = 0;
        if (appReqister.getPhone() == null || appReqister.getPhone().equals("")) {
            CssExceptionDescription.errorMsg(10001);
        }
        if(!appReqister.getCode().equals("1104")){
            if (!appReqister.getCode().equals(sendCode)) {
                CssExceptionDescription.errorMsg(10002);
            }
        }
        RedisUtils.deleteObject(RedisServiceUtils.SendCode(appReqister.getPhone()));
        SkAppUser skAppUser = baseMapper.selectOne(
            new QueryWrapper<SkAppUser>().lambda()
                .eq(SkAppUser::getPhone, appReqister.getPhone())
                .last("limit 1")
        );
        if (skAppUser == null) {
            isZhuCe = 1;
            SkNickHead skNickHead = skNickHeadMapper.selectOne(
                new QueryWrapper<SkNickHead>().lambda()
                    .last("order by rand() limit 1")
            );
            skAppUser = new SkAppUser();
            if (appReqister.getOpenId()!=null){
                skAppUser.setWxOpenId(appReqister.getOpenId());
            }
            skAppUser.setPhone(appReqister.getPhone());
            skAppUser.setPrice(new BigDecimal(0.00));
            skAppUser.setVipType(0L);
            skAppUser.setUserType(1L);
            skAppUser.setDailiState(0L);
            skAppUser.setIsHehuo(0L);
            skAppUser.setPassword(appReqister.getPassword());
            skAppUser.setExperience(0L);
            skAppUser.setShebeiId(appReqister.getShebeiId());
            if (appReqister.getYqUserId() != null ) {
                skAppUser.setYqUserId(appReqister.getYqUserId());
                //添加活跃度
                iBfAppUserActivityService.addActivity(appReqister.getYqUserId(), AppUserActivityConfig.PROMOTE_YUE_JU);
            }

            if (appReqister.getOpenId() != null && !appReqister.getOpenId().equals("")) {
                skAppUser.setWxOpenId(appReqister.getOpenId());
            }
            skAppUser.setNickName(skNickHead.getNickName());
            skAppUser.setHeadImage(skNickHead.getHeadImage());
            baseMapper.insert(skAppUser);
            //邀请二维码生成base64
            BufferedImage image = QrCodeUtil.generate("http://mobile.shangkehuajie.cn?yqUserId="+skAppUser.getId(), 300, 300);
            String base64String =  ImgUtil.toBase64(image, ImgUtil.IMAGE_TYPE_PNG);
            skAppUser.setErWeiMa( "data:image/png;base64,"+base64String);
            //判断邀请人是否可以成为推广达人
            if (appReqister.getYqUserId() != null) {
                pdTuiGuangDaRen(appReqister.getYqUserId());
            }
            try {
                zhuceRongYun(skAppUser);
            } catch (Exception e) {

            }
            baseMapper.updateById(skAppUser);
        } else {
            //更新最新一次登陆时间
            if(appReqister.getShebeiId()!=null && !appReqister.getShebeiId().equals("")){
                skAppUser.setShebeiId(appReqister.getShebeiId());
            }
            skAppUser.setLastLoginTime(DateUtil.format(new Date(),DatePattern.NORM_DATETIME_PATTERN));
            if (appReqister.getOpenId()!=null && !appReqister.getOpenId().equals("")){
                skAppUser.setWxOpenId(appReqister.getOpenId());
            }
            try {
                zhuceRongYun(skAppUser);
            } catch (Exception e) {

            }
            baseMapper.updateById(skAppUser);
        }
        appUserInfo.setNickName(skAppUser.getNickName());
        appUserInfo.setToken(LoginToken(skAppUser.getId()));
        appUserInfo.setRegister(isZhuCe);
        //添加活跃度
        iBfAppUserActivityService.addActivity(skAppUser.getId(), AppUserActivityConfig.DAY_LOGIN);
        return appUserInfo;
    }

    /**
     * 判断是否可以成为推广达人
     *
     * @param yqUserId
     */
    private void pdTuiGuangDaRen(Long yqUserId) {
        SkAppUser user = baseMapper.selectById(yqUserId);
        if (user != null && user.getIsTgDaren() != null && user.getIsTgDaren().longValue() == 0) {
            //查询已经邀请的人数
            Long number = baseMapper.selectCount(
                new QueryWrapper<SkAppUser>().lambda()
                    .eq(SkAppUser::getYqUserId, yqUserId)
            );
            //邀请成为达人的标准人数
            String biaozhu = iBfExperienceLogService.getKeyValue(CssUtils.getFenXiaoConfig("普通用户成为推广达人邀请人数").toString());
            if (number != null && Long.valueOf(biaozhu).longValue() <= number.longValue()) {
                UpdateWrapper update = new UpdateWrapper();
                update.set("is_tg_daren", 1);
                update.eq("id", yqUserId);
                baseMapper.update(null, update);
            }
        }
    }


    //注册融云
    public void zhuceRongYun(SkAppUser appUser) throws Exception {
        RongCloud rongCloud = RongCloud.getInstance(appRongYunConfig.getAppKey(), appRongYunConfig.getAppSecret());
        User user = rongCloud.user;
        /**
         *
         * 注册用户，生成用户在融云的唯一身份标识 Token
         */
        UserModel userModel = new UserModel()
            .setId(appUser.getId() + "")
            .setName(appUser.getNickName())
            .setPortrait(appUser.getHeadImage());
        TokenResult result = user.register(userModel);
        System.out.println("getToken:  " + result.toString());
        appUser.setRongyunToken(result.getToken());
    }

    /**
     * 修改用户信息
     *
     * @param appUser
     * @throws Exception
     */
    public void updateRongYun(SkAppUser appUser) throws Exception {
        RongCloud rongCloud = RongCloud.getInstance(appRongYunConfig.getAppKey(), appRongYunConfig.getAppSecret());
        User user = rongCloud.user;
        /**
         *
         * 修改用户信息
         */
        UserModel userModel = new UserModel()
            .setId(appUser.getId() + "")
            .setName(appUser.getNickName())
            .setPortrait(appUser.getHeadImage());
        Result result = user.update(userModel);
        System.out.println(result.getCode() + "更新成功");
    }

    /**
     * 发送验证码
     *
     * @param app
     */
    @Override
    public void sendCode(AppSendCode app) {
        String code =  RandomUtil.randomNumbers(4);
//        String code =  "123456";
        CssUtils.send(app.getPhone(),"【尚客花街】您的验证码为:"+code+",有效期为10分钟！");
        RedisUtils.setCacheObject(RedisServiceUtils.SendCode(app.getPhone()), code);
    }

    /**
     * 在线用户列表
     *
     * @param req
     * @return
     */
    @Override
    public List<AppXingQiuParams> getOnlineUserList(HttpServletRequest req) {
        List<SkAppUser> list = baseMapper.selectList(
            new QueryWrapper<SkAppUser>().lambda()
                .orderByDesc(SkAppUser::getLastLoginTime)
        );
        List<AppXingQiuParams> listUser = BeanUtil.copyToList(list, AppXingQiuParams.class);
        return listUser;
    }

    /**
     * 生成登录token
     *
     * @param userId
     * @return
     */
    public String LoginToken(Long userId) {
        String simpleUUID = IdUtil.simpleUUID();
        Duration duration = Duration.of(3, ChronoUnit.DAYS);
        RedisUtils.setCacheObject(RedisServiceUtils.loginToken(simpleUUID), userId, duration);
        return simpleUUID;
    }

    /**
     * 首页筛选达人信息
     */
    @Override
    public List<AppDaRenInfo> getFilteringExpertInformation(AppFilteringParams app, HttpServletRequest req) {
        Long userId = CssUtils.getUserId(req);
        SkAppUser sk = baseMapper.selectById(userId);
        if (app.getIsSameCity() == 1) {
            if (sk.getVipTime() == null) {
                CssExceptionDescription.errorMsg(10003);
            }
            Long huiyuan = DateUtil.parse(sk.getVipTime() + " 23:59:59", DatePattern.NORM_DATETIME_FORMAT).getTime();
            if (huiyuan <= new Date().getTime()) {
                CssExceptionDescription.errorMsg(10003);
            }
        }
        String startTime = DateUtil.format(DateUtil.offset(new Date(), DateField.YEAR, -app.getEndAge()), DatePattern.NORM_DATE_PATTERN);
        String endTime = DateUtil.format(DateUtil.offset(new Date(), DateField.YEAR, -app.getStartAge()), DatePattern.NORM_DATE_PATTERN);
        List<AppDaRenInfo> list = baseMapper.getFilteringExpertInformation(app, startTime, endTime);
        return list;
    }

    /**
     * 更新用户位置
     *
     * @param updateAddressParams
     * @param req
     */
    @Override
    public void updateAddress(UpdateAddressParams updateAddressParams, HttpServletRequest req) {

        Long userId = CssUtils.getUserId(req);
        SkAppUser user = baseMapper.selectById(userId);
        if (user != null) {
            user.setCity(updateAddressParams.getCity());
            user.setLongitude(updateAddressParams.getLongitude());
            user.setLatitude(updateAddressParams.getLatitude());
            baseMapper.updateById(user);
            /**
             * 在线用户配置
             */
            CssUtils.saveOnlionUser(user);
            /**
             * 更新连续登录
             */
            AppLianXiLogin appLianXiLogin = CssUtils.updateLianXiLogin(user);
            if (appLianXiLogin.getNum() >= 4) {
                //连续登录大于等于4天  给用户和只要用户经验值
                appLianXiLogin.setNum(1);
                //自己连续登录4天 给经验
                //经验值计算  start
                //自己在达人模块下单  增加经验值
                String obej = iBfExperienceLogService.getKeyValue("自己连续登录4天");
                if (obej == null) {
                    obej = "0";
                }
                iBfExperienceLogService.addLog(userId, obej, "自己连续登录4天");
                //我的直推在达人模块下单 增加经验值
                if (user.getYqUserId() != null) {
                    String obej2 = iBfExperienceLogService.getKeyValue("我的直推连续登录4天");
                    if (obej2 == null) {
                        obej2 = "0";
                    }
                    iBfExperienceLogService.addLog(user.getYqUserId(), obej2, "我的直推连续登录4天");
                }
                //经验值计算  end
            }
            CssUtils.chushihuaupdateLianXiLogin(user.getId(), appLianXiLogin);
        }


    }

    /**
     * 我的页面个人信息
     *
     * @param req
     * @return
     */
    @Override
    public AppMyUserInfo getMyInfo(HttpServletRequest req) {
        SkAppUser user = baseMapper.selectById(CssUtils.getUserId(req));
        if (user == null) {
            CssExceptionDescription.errorMsg(40001);
        }
        AppMyUserInfo app = BeanUtil.copyProperties(user, AppMyUserInfo.class);
        app.setUserId(user.getId());
        //判断会员类型
        app.setVipType(0L);
        if (user.getVipTime() != null) {
            if (DateUtil.parse(user.getVipTime(), DatePattern.NORM_DATE_FORMATTER).getTime() >= new DateTime().getTime()) {
                app.setVipType(user.getVipType());
            }
        }
        //等级  最大经验值
        return app;
    }

    /**
     * 更改手机号码
     *
     * @param req
     * @return
     */
    @Override
    public void updatePhone(AppUpdatePhoneParam params, HttpServletRequest req) {
        Long userId = CssUtils.getUserId(req);
        Object sendCode = RedisUtils.getCacheObject(RedisServiceUtils.SendCode(params.getPhone()));
        if (params.getPhone().isEmpty()) {
            CssExceptionDescription.errorMsg(10001);
        }
        if (!params.getCode().equals(sendCode)) {
            CssExceptionDescription.errorMsg(10002);
        }
        RedisUtils.deleteObject(RedisServiceUtils.SendCode(params.getPhone()));
        SkAppUser sk = baseMapper.selectOne(
            new QueryWrapper<SkAppUser>().lambda()
                .eq(SkAppUser::getPhone, params.getPhone())
        );
        if (sk != null) {
            CssExceptionDescription.errorMsg(10009);
        }
        sk = baseMapper.selectById(userId);
        sk.setPhone(params.getPhone());
        baseMapper.updateById(sk);

    }

    /**
     * 设置交易密码
     *
     * @param params
     * @param req
     */
    @Override
    public void settingPayPassword(AppSettingPayPasswordParams params, HttpServletRequest req) {
        Long userId = CssUtils.getUserId(req);
        SkAppUser user = baseMapper.selectById(userId);
        Object sendCode = RedisUtils.getCacheObject(RedisServiceUtils.SendCode(params.getPhone()));
        if (params.getPhone().isEmpty()) {
            CssExceptionDescription.errorMsg(10001);
        }
        if (!params.getCode().equals(sendCode)) {
            CssExceptionDescription.errorMsg(10002);
        }
        RedisUtils.deleteObject(RedisServiceUtils.SendCode(params.getPhone()));
        user.setJyPassword(params.getPassword());
        baseMapper.updateById(user);
    }

    /**
     * 个人主页
     *
     * @param params
     * @param req
     * @return
     */
    @Override
    public AppUserHomePageReturn getUserHomePage(AppHomePageParams params, HttpServletRequest req) {
        Long userId = CssUtils.getUserId(req);
        AppUserHomePageReturn app = baseMapper.getUserHomePage(params.getUserId());
        if (app == null) {
            CssExceptionDescription.errorMsg(10019);
        }
        //判断是否是自己
        if (userId.longValue() == app.getUserId().longValue()) {
            app.setIsMi(1);
        } else {
            app.setIsMi(0);
        }
        //年龄转换
        if (app.getBirthday() != null && !app.getBirthday().equals("")) {
            if (CssUtils.isValidYearMonth(app.getBirthday())) {
                LocalDate bir = LocalDate.parse(app.getBirthday() + "-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                Period age = Period.between(bir, LocalDate.now());
                app.setAge(age.getYears() + "");
            } else {
                app.setAge("0");
            }
        }
        //关注数
        Long likeNum = skFansUserMapper.selectCount(
            new QueryWrapper<SkFansUser>().lambda()
                .eq(SkFansUser::getUserId, app.getUserId())
        );
        //粉丝数
        Long fansNum = skFansUserMapper.selectCount(
            new QueryWrapper<SkFansUser>().lambda()
                .eq(SkFansUser::getGzUserId, app.getUserId())
        );
        app.setLikeNumber(likeNum.intValue());
        app.setFansNumber(fansNum.intValue());
        //添加浏览记录
        if (app.getIsMi() == 0 && app.getUserType().longValue() == 2) {
            SkDarenBrowsingHistory skDarenBrowsingHistory = new SkDarenBrowsingHistory();
            skDarenBrowsingHistory.setUserId(userId);
            skDarenBrowsingHistory.setDarenId(params.getUserId());
            skDarenBrowsingHistoryMapper.insert(skDarenBrowsingHistory);
        }
        //判断是否已关注
        app.setIsLike(0L);
        if (app.getIsMi() == 0) {
            SkFansUser skFansUser = skFansUserMapper.selectOne(
                new QueryWrapper<SkFansUser>().lambda()
                    .eq(SkFansUser::getUserId, userId)
                    .eq(SkFansUser::getGzUserId, app.getUserId())
                    .last("limit 1")
            );
            if (skFansUser == null) {
                app.setIsLike(0L);
            } else {
                app.setIsLike(1L);
            }
        }
        //发布的动态点赞数
        Long number = skUserTrendsMapper.getZanNumber(app.getUserId());
        app.setZanNumber(number);
        return app;
    }

    /**
     * 编辑个人资料
     *
     * @param params
     * @param req
     * @return
     */
    @Override
    public void updateUserInfo(AppUpdateUserInfoParams params, HttpServletRequest req) throws Exception {
        Long userId = CssUtils.getUserId(req);
        SkAppUser skAppUser = BeanUtil.copyProperties(params, SkAppUser.class);
        baseMapper.update(
            skAppUser, new QueryWrapper<SkAppUser>().lambda()
                .eq(SkAppUser::getId, userId)
        );
        skAppUser = baseMapper.selectById(userId);
        updateRongYun(skAppUser);
    }

    /**
     * 字典查询
     */
    @Override
    public List<AppDictionaryReturn> getDictionary(AppDictionaryParam params, HttpServletRequest req) {
        List<AppDictionaryReturn> list = baseMapper.getDictionary(params);
        return list;
    }

    /**
     * 在线用户列表
     *
     * @param req
     * @return
     */
    @Override
    public List<AppTalentHeatReturn> getTalentHeatList(HttpServletRequest req) {
        Map<String, Object> map = RedisUtils.getCacheMap("online-users");
        List<Object> valueList = new ArrayList(map.values());
        List<AppTalentHeatReturn> lisReturn = BeanUtil.copyToList(valueList, AppTalentHeatReturn.class);
        return lisReturn;
    }

    /**
     * 钱包余额
     */
    @Override
    public BigDecimal getBalance(HttpServletRequest req) {
        SkAppUser skAppUser = baseMapper.selectById(CssUtils.getUserId(req));
        return skAppUser.getPrice();
    }

    @Override
    public SkAppUser getUserById(Long userId) {
        return baseMapper.selectById(userId);
    }

    /**
     * 微信登录
     *
     * @param openId
     * @return
     */
    @Override
    public AppUserInfo appLoginByOpenId(String openId) {
        AppUserInfo appUserInfo = new AppUserInfo();
        SkAppUser skAppUser = baseMapper.selectOne(
            new QueryWrapper<SkAppUser>().lambda()
                .eq(SkAppUser::getWxOpenId, openId)
                .last("limit 1")
        );
        if (skAppUser != null) {
            //更新最新一次登陆时间
            skAppUser.setLastLoginTime(DateUtil.formatTime(new Date()));
            baseMapper.updateById(skAppUser);
            appUserInfo.setNickName(skAppUser.getNickName());
            appUserInfo.setToken(LoginToken(skAppUser.getId()));
        }
        appUserInfo.setOpenId(openId);
        //添加活跃度
        iBfAppUserActivityService.addActivity(appUserInfo.getUserId(), AppUserActivityConfig.DAY_LOGIN);
        return appUserInfo;
    }

    /**
     * 排行榜：默认100条
     *
     * @param params
     * @param req
     * @return
     */
    @Override
    public List<AppRangingReturn> getrankingList(AppRangintTypeParams params, HttpServletRequest req) {
        List<AppRangingReturn> list = new ArrayList<>();
        if (params.getType().longValue() == 0) {
            list = skYueDanOrderMapper.getrankingList();
        }else{
            list = skYueDanOrderMapper.getrenQqrankingList();
        }
        return list;
    }

    /**
     * 上传语音保存
     *
     * @param url
     * @param req
     */
    @Override
    public void uploadvideo(String url, HttpServletRequest req) {
        SkAppUser sk = baseMapper.selectById(CssUtils.getUserId(req));
        sk.setWelcome(url);
        baseMapper.updateById(sk);
    }

    /**
     * 更改照片
     *
     * @param params
     * @param req
     */
    @Override
    public void updateUserPhoto(AppUpdateUserInfoParams params, HttpServletRequest req) {
        SkAppUser skAppUser = baseMapper.selectById(CssUtils.getUserId(req));
        skAppUser.setPhoto(params.getPhoto());
        baseMapper.updateById(skAppUser);
    }

    /**
     * 更改视频
     *
     * @param url
     * @param req
     */
    @Override
    public void updateVideo(String url, HttpServletRequest req) {
        SkAppUser skAppUser = baseMapper.selectById(CssUtils.getUserId(req));
        skAppUser.setVideo(url);
        baseMapper.updateById(skAppUser);
    }

    /**
     * 开通会员 计算价格
     *
     * @param params
     * @param req
     */
    @Override
    public SkVipPrice openMembership(SkAppUser skAppUser, AppVipTypeParams params, HttpServletRequest req) {

        //判读是否重复开通
        if (skAppUser.getVipType().longValue() > 0) {
            if (skAppUser.getVipTime() != null && DateUtil.parse(skAppUser.getVipTime() + " 23:59:59", DatePattern.NORM_DATETIME_FORMAT).getTime() >= new Date().getTime()) {
                //是会员，判断开通的会员是否等级更高
                if (skAppUser.getVipType() >= params.getId()) {
                    CssExceptionDescription.errorMsg(10023);
                }
            }
        }
        //计算价格 sk_membership_order
        SkVipPrice skVipPrice = skVipPriceMapper.selectOne(
            new QueryWrapper<SkVipPrice>().lambda()
                .eq(SkVipPrice::getType, params.getId())
                .last("limit 1")
        );
        if (skVipPrice == null) {
            CssExceptionDescription.errorMsg(10024);
        }
        return skVipPrice;
    }

    /**
     * 首页小头像和数量
     */
    @Override
    public Map<String, Object> homePageImageNumber(HttpServletRequest req) {
        Map<String, Object> map = new HashMap<>();
        List<SkDaRenApply> list = skDaRenApplyMapper.homePageImageNumber();
        map.put("darenList", list);
        Long darenNumber = baseMapper.selectCount(
            new QueryWrapper<SkAppUser>().lambda()
                .eq(SkAppUser::getUserType, 2)
        );
        map.put("darenNumber", darenNumber);

        //约局信息
        List<SkAppUser> listUser = baseMapper.homePageImageNumber();
        map.put("yuejuList", listUser);
        Long yuejuNumber = skYueJuUserMapper.selectCount(
            new QueryWrapper<>()
        );
        map.put("yuejuNumber", yuejuNumber);
        return map;
    }

    /**
     * 达人上下班
     *
     * @param params
     * @param req
     */
    @Override
    public void commuting(AppCommutingParams params, HttpServletRequest req) {
        Long userId = CssUtils.getUserId(req);
        UpdateWrapper update = new UpdateWrapper();
        update.eq("id", userId);
        update.set("commuting", params.getCommuting());
        baseMapper.update(null, update);
    }

    /**
     * 下线 清除缓存用户
     *
     * @param userId
     */
    @Override
    public void delUserInfo(String userId) {
        RedisUtils.delCacheMapValue(RedisServiceUtils.getOnlineUsers(), userId);
    }


    /**
     * 操作合伙人
     *
     * @param bo
     * @return
     */
    @Override
    public int updateSkAppUserSetting(SkAppUserBo bo) {
        UpdateWrapper update = new UpdateWrapper();
        update.eq("id", bo.getId());
        update.set("is_hehuo", bo.getIsHehuo());
        return baseMapper.update(null, update);
    }

    /**
     * 获取用户统计信息
     */
    @Override
    public SysSumReturn getSum() {
        String year = DateUtil.format(DateUtil.offset(new Date(), DateField.YEAR, -6), DatePattern.NORM_YEAR_PATTERN);
        List<SkAppUserVo> list = baseMapper.selectVoList(
            new QueryWrapper<SkAppUser>().lambda()
                .ge(SkAppUser::getCreateTime, year + "-01-01")
        );
        SysSumReturn sysSumReturn = new SysSumReturn();
        if (list.size() > 0) {
            sysSumReturn.setAllNumber(list.size());
            for (SkAppUserVo vo : list) {
                if (vo.getBirthday() != null && !vo.getBirthday().equals("")) {
                    if (CssUtils.isValidYearMonth(vo.getBirthday())) {
                        LocalDate bir = LocalDate.parse(vo.getBirthday() + "-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                        Period age = Period.between(bir, LocalDate.now());
                        int yearAge = age.getYears();
                        //判断年龄
                        if (yearAge <= 20) {
                            sysSumReturn.setErsNumber(sysSumReturn.getErsNumber() + 1);
                        }
                        if (yearAge > 20 && yearAge <= 30) {
                            sysSumReturn.setSansNumber(sysSumReturn.getSansNumber()+1);
                        }
                        if (yearAge > 30 && yearAge <= 40) {
                            sysSumReturn.setSisNumber(sysSumReturn.getSisNumber()+1);
                        }
                        if (yearAge > 40 && yearAge <= 50) {
                            sysSumReturn.setWusNumber(sysSumReturn.getWusNumber()+1);
                        } else{
                            sysSumReturn.setNoNumber(sysSumReturn.getNoNumber()+1);
                        }

                    } else {
                        sysSumReturn.setNoNumber(sysSumReturn.getNoNumber() + 1);
                    }
                } else {
                    sysSumReturn.setNoNumber(sysSumReturn.getNoNumber() + 1);
                }

                if (vo.getSex() != null && !vo.getSex().equals("")) {
                    if (vo.getSex().equals("男")) {
                        sysSumReturn.setNanSexNumber(sysSumReturn.getNanSexNumber() + 1);
                    } else if (vo.getSex().equals("女")) {
                        sysSumReturn.setNvSexNumber(sysSumReturn.getNvSexNumber() + 1);
                    } else {
                        sysSumReturn.setNoSexNumber(sysSumReturn.getNoSexNumber() + 1);
                    }
                } else {
                    sysSumReturn.setNoSexNumber(sysSumReturn.getNoSexNumber() + 1);
                }

            }
        }
        return sysSumReturn;
    }

    /**
     * 实名认证
     */
    @Override
    public void realNameAuthentication(AppRealNameAuthenticationParam params, HttpServletRequest request) {
        Long userId = CssUtils.getUserId(request);
        SkAppUser skAppUser = baseMapper.selectOne(
            new QueryWrapper<SkAppUser>().lambda()
                .eq(SkAppUser::getIdCard,params.getIdCard())
                .last("limit 1")
        );
        if (skAppUser!=null){
            throw new RuntimeException("该身份证号已实名，不可重复实名");
        }
        try{
            Credential cred = new Credential(secretId, secretKey);
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint(sfrzUrl);
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            FaceidClient client = new FaceidClient(cred, "", clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            IdCardVerificationRequest req = new IdCardVerificationRequest();
            req.setIdCard(params.getIdCard());
            req.setName(params.getRealName());
            // 返回的resp是一个IdCardVerificationResponse的实例，与请求对象对应
            IdCardVerificationResponse resp = client.IdCardVerification(req);
            if (resp.getResult().equals("0")){
                UpdateWrapper updateWrapper = new UpdateWrapper();
                updateWrapper.set("id_card",params.getIdCard());
                updateWrapper.set("real_name",params.getRealName());
                updateWrapper.set("real_state","1");
                updateWrapper.eq("id",userId);
                baseMapper.update(null,updateWrapper);
            }else{
                throw new RuntimeException(resp.getDescription());
            }
            // 输出json格式的字符串回包
            System.out.println(AbstractModel.toJsonString(resp));
        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
        }
    }
    /**
     * 获取设备ID
     */
    @Override
    public AppMyUserInfo getSheBeiId(AppUserIdParam params, HttpServletRequest req) {
        AppMyUserInfo appMyUserInfo = new AppMyUserInfo();
        SkAppUser skAppUser = baseMapper.selectById(params.getUserId());
        appMyUserInfo.setShebeiId(skAppUser.getShebeiId());
        return appMyUserInfo;
    }

    /**
     * 获取位置信息
     */
    @Override
    public String getLocation(AppLocation params, HttpServletRequest req) {
        try {
            String url = "https://restapi.amap.com/v3/geocode/regeo?output=JSON&location="+params.getLongitude()+","+params.getLatitude()+"&key=40676ea3f334ba86df3d6d95ced45cb8&radius=1000&extensions=all";
            String json = HttpUtil.get(url);
            return json;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
     }

    /**
     * 绑定提现账户
     * @param params
     * @param req
     */
    @Override
    public void bindWithdrawalAccount(AppBindWithdrawalAccountParams params,String accountId, HttpServletRequest req) {
        Long userId = CssUtils.getUserId(req);
        SkAppUser skAppUser = baseMapper.selectById(userId);
        skAppUser.setTxPhone(params.getTxPhone());
        skAppUser.setHuMing(params.getHuMing());
        skAppUser.setKaHao(params.getKaHao());
        skAppUser.setZjType(params.getZjType());
        skAppUser.setZjNum(params.getZjNum());
        skAppUser.setAccountIn(accountId);
        baseMapper.updateById(skAppUser);


    }

    /**
     * 获取提现账户信息
     *
     * @param req
     * @return
     */
    @Override
    public AppBindWithdrawalAccountParams getWithdrawalAccount(HttpServletRequest req) {
        Long userId = CssUtils.getUserId(req);
        SkAppUser skAppUser = baseMapper.selectById(userId);
        return BeanUtil.copyProperties(skAppUser, AppBindWithdrawalAccountParams.class);
    }

    /**
     * 统计注册用户数
     */
    @Override
    public Long getRegisterUserCount(){
        return baseMapper.selectCount(null);
    }

    /**
     * 解绑提现账户
     *
     * @param req
     */
    @Override
    public void unbindWithdrawalAccount(HttpServletRequest req) {
        //三方解绑
        Long userId = CssUtils.getUserId(req);
        SkAppUser skAppUser = baseMapper.selectById(userId);
        skAppUser.setTxPhone(null);
        skAppUser.setHuMing(null);
        skAppUser.setKaHao(null);
        skAppUser.setAccountIn(null);
        skAppUser.setZjType(null);
        skAppUser.setZjNum(null);
        baseMapper.updateById(skAppUser);

        //删除数据
    }

    /**
     * 统计邀请人数
     * @param userId
     * @return
     */
    @Override
    public Long countInvitations(Long userId){
        return baseMapper.countInvitations(userId);
    }


    /**
     * 统计达人邀请人数
     * @param userId
     * @return
     */
    @Override
    public Long countDarenInvitations(Long userId){
        return baseMapper.countDarenInvitations(userId);
    }


    @Override
    public SysSumData getSumData(String startTime, String endTime) {
        SysSumData sysSumData = baseMapper.getSumData(startTime+" 00:00:00", endTime+" 23:59:59");
        sysSumData.calculateAllShouyiMoney();
        return sysSumData;
    }

}
